// 递归遍历对象：过滤对象中为null/undefined/''/[]/{}的属性值 

// 函数防抖
export function debounce(fn, delay = 300) {
    let timer = null;
    return function(...args) {
        if (timer !== null) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay)
    }
}

// 函数节流
export function throttle(fn, delay = 300) {
    let valid = true
    return function(...args) {
        if (!valid) {
            //休息时间 暂不接客
            return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn.apply(this, args);
            valid = true;
        }, delay)
    }
}

// 判空处理 参数可以是数组或对象
export const isEmpty = (obj) => {
    // 参数为字符串时
    if ((obj + '').trim() === "undefined" || (obj + '').trim() === "null" || (obj + '').trim() === "" || (obj + '').trim() === 'NaN') {
        return true
    }
    // 参数为对象时 且不能空对象
    if (!obj || !typeof obj === "object") return true;

    const keys = Object.keys(obj);
    for (var key of keys) {
        const val = obj[key];

        if ((val + '').trim() === "undefined" || (val + '').trim() === "null" || (val + '').trim() === "" || (val + '').trim() === 'NaN') {
            // 如属性值为null或undefined或''或NaN 都表示为空
            return true
        } else if (typeof val === "object") {
            if (Object.keys(obj[key]).length === 0) {
                // 如属性值为空数组、空对象 也表示为空
                return true
            }
            // 属性值为对象，递归调用
            isEmpty(obj[key]);
        }
    }
    return false;
}

// 时间戳转字符串
export function getTimeStamp(time) {
    return time ? getString(time.getTime()) : null;
};
// 转数字
export function getNumber(number) {
    return number !== '' ? parseInt(number) : null;
};
// 转字符串
export function getString(string) {
    return string ? string.toString() : null;
};

// 时间戳转2020-04-14或2020/04/14等格式
export function dateFormat(dateStr, pattern = "", link = '-') {
    if (!dateStr) {
        return '';
    }
    var dt = new Date(parseInt(dateStr));
    var y = dt.getFullYear();
    var m = (dt.getMonth() + 1).toString().padStart(2, 0);
    var d = dt
        .getDate()
        .toString()
        .padStart(2, 0);
    if (pattern.toLowerCase() === "yyyy-mm-dd") {
        return `${y}${link}${m}${link}${d}`;
    } else {
        var hh = dt
            .getHours()
            .toString()
            .padStart(2, 0);
        var mm = dt
            .getMinutes()
            .toString()
            .padStart(2, 0);

        var ss = dt
            .getSeconds()
            .toString()
            .padStart(2, 0);
        return `${y}${link}${m}${link}${d} ${hh}:${mm}:${ss}`;
    }
}


export function formatDate(format = "Y-M-D h:m:s", timestamp = Date.now()) {
    let date = new Date(timestamp);
    let dateInfo = {
        Y: date.getFullYear(),
        M: date.getMonth() + 1,
        D: date.getDate(),
        h: date.getHours(),
        m: date.getMinutes(),
        s: date.getSeconds(),
    };
    let formatNumber = (n) => (n >= 10 ? n : "0" + n);
    let res = format
        .replace("Y", dateInfo.Y)
        .replace("M", formatNumber(dateInfo.M))
        .replace("D", formatNumber(dateInfo.D))
        .replace("h", formatNumber(dateInfo.h))
        .replace("m", formatNumber(dateInfo.m))
        .replace("s", formatNumber(dateInfo.s));
    return res;
}

// 时间戳转中国标准时间格式【Tue Apr 13 2021 00:00:00 GMT+0800 (中国标准时间)】
export function timstampToStandardDate(timestamp) {
    if (!timestamp) {
        return ''
    }
    return new Date(getNumber(timestamp))
}
// 中国标准时间格式【Tue Apr 13 2021 00:00:00 GMT+0800 (中国标准时间)】转为时间戳
export function standardDateToTimstamp(standarddate) {
    console.log(standarddate);
    return getNumber(+new Date(standarddate));
}

// 获取本地上传的图片文件的url txt文件路径也可以得到
// File对象转 blob 协议的地址
export function getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

// Javascript读取本地txt文件
export function getFileContent(url) {
    let xhr = new XMLHttpRequest(),
        okStatus = document.location.protocol === "file:" ? 0 : 200;
    xhr.open('GET', url, false);
    xhr.overrideMimeType("text/html;charset=utf-8"); // 默认为utf-8
    xhr.send(null);
    return xhr.status === okStatus ? xhr.responseText : null;
}

// 获取所有id; 类似 ids = 1,2,3
export function getAllID(array = []) {
    var tempIds = '';
    array = Array.from(array);
    if (array && array.length && array.length > 0) {
        array.map(item => {
            tempIds += item.id + ',';
        })
    }
    return tempIds.slice(0, -1);;
}
// js 产生任意位数的随机数
export function RndNum(n) {
    var rnd = "";
    for (var i = 0; i < n; i++) {
        rnd += Math.floor(Math.random() * 10);
    }
    return parseInt(rnd);
}

export function objTostring(obj) {
    var str = '';
    for (var key in obj) {
        str += key + '=' + obj[key] + '&';
    }
    return str.slice(0, -1);
}

// 关闭当前标签页
export function closeActiveTag() {
    var lis = document.querySelectorAll('.content-box .tags ul .tags-li');
    lis = [...lis];
    var activeIndex = lis.findIndex(item => {
        return item.classList.contains('active');
    });
    var tempArr = [...this.tagsList];
    tempArr.splice(activeIndex, 1);
    this.SET_TAGSLIST(tempArr);
}

// 设置当前标签页
export function setActiveTag(name) {
    var lis = document.querySelectorAll('.content-box .tags ul .tags-li');
    lis = [...lis];
    var activeIndex = lis.findIndex(item => {
        return item.classList.contains('active');
    });
    var tempArr = [...this.tagsList];
    // tempArr[activeIndex].title = this.form.name;
    if (name.length <= 6) {
        tempArr[activeIndex].title = name;
    } else {
        tempArr[activeIndex].title = name.slice(0, 6) + '...';
    }

    this.SET_TAGSLIST(tempArr);
}
// 将URL参数解析为JSON对象
export function parseQueryString(url) {
    var obj = {};
    var keyvalue = [];
    var key = "",
        value = "";
    var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
    for (var i in paraString) {
        keyvalue = paraString[i].split("=");
        key = keyvalue[0];
        value = keyvalue[1];
        obj[key] = value;
    }
    return obj;
}
// 数字格式转换成千分位
export function commafy(num) {
    if ((num + "").trim() == "") {
        return "";
    }
    if (isNaN(num)) {
        return "";
    }
    num = num + "";
    if (/^.*\..*$/.test(num)) {
        varpointIndex = num.lastIndexOf(".");
        varintPart = num.substring(0, pointIndex);
        varpointPart = num.substring(pointIndex + 1, num.length);
        intPart = intPart + "";
        var re = /(-?\d+)(\d{3})/;
        while (re.test(intPart)) {
            intPart = intPart.replace(re, "$1,$2");
        }
        num = intPart + "." + pointPart;
    } else {
        num = num + "";
        var re = /(-?\d+)(\d{3})/;
        while (re.test(num)) {
            num = num.replace(re, "$1,$2");
        }
    }
    return num;
}
// 参数1: 原对象数据
// 参数2: 从原对象选出需要的字段名
// 参数3: 原字段名修改后的字段名
// 参数4: 选出来的原字段名不存在时 用该数据占位

export function chooseFields(object, props_l = [], props_c = {}, props_r = {}) {
    let retObj = {};
    let dataArr = Object.keys(object);
    let modeifyArr = Object.keys(props_c);
    // 说明含有需要调整的字段名
    if (Object.keys(props_c).length > 0) {
        props_l.forEach((item, index) => {
            if (dataArr.includes(item) === true) {
                if (modeifyArr.includes(item)) {
                    retObj[props_c[item]] =
                        typeof object[item] === "object" && object[item] != null ?
                        JSON.parse(JSON.stringify(object[item])) :
                        object[item];
                } else {
                    retObj[item] =
                        typeof object[item] === "object" && object[item] != null ?
                        JSON.parse(JSON.stringify(object[item])) :
                        object[item];
                }
            } else {
                // 返回数据缺少需要的字段, 设置默认值
                if (modeifyArr.includes(item)) {
                    retObj[props_c[item]] = props_r[props_c[item]];
                } else {
                    retObj[item] = props_r[item];
                }
            }
        });
    } else {
        // 说明没有需要调整的字段名
        props_l.forEach((item, index) => {
            if (dataArr.includes(item) === true) {
                retObj[item] =
                    typeof object[item] === "object" && object[item] != null ?
                    JSON.parse(JSON.stringify(object[item])) :
                    object[item];
            } else {
                // 返回数据缺少需要的字段, 设置默认值
                retObj[item] = props_r[item];
            }
        });
    }
    return retObj;
}

// 删除对象中属性值为 null、undefined、""、NaN字段 排除 0、false
export function removeField(obj) {
    const keyArr = Object.keys(obj);

    if (keyArr.length === 0) {
        return obj;
    }

    keyArr.forEach(k => {
        if ((obj[k] + '').trim() === "undefined" || (obj[k] + '').trim() === "null" || (obj[k] + '').trim() === '' || (obj[k] + '').trim() === 'NaN')
            delete obj[k];
    });
    return obj;
}

// js封装--操作localStorage本地存储
export const storage = {
    set(key, value) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    get(key) {
        return JSON.parse(localStorage.getItem(key));
    },
    remove(key) {
        localStorage.removeItem(key);
    }
}


// 获取图片的原始尺寸大小
export function getImgNaturalDimensions(oImg, callback) {
    var nWidth, nHeight;
    if (!oImg.naturalWidth) { // 现代浏览器

        nWidth = oImg.naturalWidth;
        nHeight = oImg.naturalHeight;
        callback && callback({ w: nWidth, h: nHeight });

    } else { // IE6/7/8
        var nImg = new Image();

        nImg.onload = function() {
            var nWidth = nImg.width,
                nHeight = nImg.height;
            callback && callback({ w: nWidth, h: nHeight });
        }

        nImg.src = oImg.src;
    }
}

import Cookies from 'js-cookie';
import { resetRouter } from '@/router'
export function resetTokenAndClearUser() {
    // 退出登陆 清除用户资料
    // localStorage.setItem('token', '')
    // localStorage.setItem('userImg', '')
    // localStorage.setItem('userName', '')
    Cookies.remove('access_token');
    Cookies.remove('refresh_token');
    // 重设路由
    resetRouter()
}


// 公共请求方法 如果返回的数据需要公共起来 那么需要把公共请求方法放在store维护
export { getTextTest, getImgTest, getImgTest_plus, handleLock, handleUnlock, getSidebar }
from '@/api/index';